<template>
  <div class="page">
    <div class="title-wrap">
      <h3 class="sub-title success-color">
        统计号码的历史记录
      </h3>
    </div>
    <div class="container">
      <div class="history-container">
        <div
          class="history-item"
          v-for="(historyItem, index) in historyList"
          :key="index"
        >
          <!-- <div class="date">{{ historyItem.date }}</div> -->
          <div class="item-wrap">
            <div class="label">号码：</div>
            <div class="value">{{ historyItem.numList.join(',') }}</div>
          </div>
          <div class="item-wrap">
            <div class="label">数量：</div>
            <div class="value">单选数量【{{ historyItem.times.danXuanNum }}】，组选数量【{{
              historyItem.times.zuXuanNum
            }}】，复式单选数量【{{ historyItem.times.fuDanNum }}】</div>
          </div>
          <div class="item-wrap">
            <div class="label">操作：</div>
            <div class="label">
              <el-button
                type="danger"
                link
                @click="deleteThisHistory(historyItem)"
              >
                删除此记录
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <div class="btn-group">
        <el-button type="primary" @click="startComputed">统计次数</el-button>
      </div>
      <div class="result-wrap" v-if="finalResult">
        <div class="title">
          结果如下:
          <span class="link-btn" @click="downloadFile">下载txt结果</span>
          <span class="link-btn" @click="downloadExcel">下载表格结果</span>
        </div>
        <!-- <div class="tools-wrap">
          <div class="label">排序方式：</div>
          <div class="value">
            <el-radio-group v-model="sortType" @change="sortResult">
              <el-radio :value="1">升序</el-radio>
              <el-radio :value="2">降序</el-radio>
            </el-radio-group>
          </div>
        </div> -->
        <div class="result-list-wrap">
          <div
            class="result-item"
            v-for="(item, index) in finalResult"
            :key="index"
          >
            <div class="label">{{ item.number }}</div>
            :
            <div class="res-value">{{ item.times }}</div>
          </div>
        </div>
        <!-- <div class="title">详情如下:<span class="link-btn" @click="downloadFile">下载结果</span></div>
        <div class="result-list-wrap">
          <div class="result-item" v-for="(item,key) in result" :key="key">
            {{ key }}： <span class="res-value">{{ item }}（次）</span>
          </div>
        </div> -->
      </div>
    </div>
  </div>
</template>
<script>
import { splitCharOptions } from '@/utils/constant'
import { ElMessage } from 'element-plus'
import {
  downFile,
  getShortTodayStr,
  numToString,
  chineseNumToNumber
} from '../utils/tools'
import { isReqOverflow } from '../utils/userLimit'
import * as XLSX from 'xlsx-js-style'
import { adminDialog } from '@/components/adminDialog'
import { request } from '@/api/fetch'
import { onMounted } from 'vue';
import {  getUserInfo } from '@/utils/auth.js'
export default {
  data() {
    return {
      historyList: [
        {
          numList: [123, 456],
          times: {
            danXuanNum: 1,
            zuXuanNum: 1,
            zu3Num: 0,
            zu6Num: 0,
            fuDanNum: 0
          }
        },
        {
          numList: [876],
          times: {
            danXuanNum: 0,
            zuXuanNum: 0,
            zu3Num: 0,
            zu6Num: 0,
            fuDanNum: 1
          }
        }

      ],
      finalResult: null
    }
  },
  methods: {
    startComputed() {
      let allNums = this.spreadNums()
      this.countAllNumsTime(allNums)
    },
    getSpreadZuNums(numStr){
      // 可能是组3 也可能是组6
      // 123 [1,2,3]
      let numList = String(numStr).split('')
      // let numSet = new Set(numList)
      let len = numList.length
      let resNumList = []
      // 如果存在相同数组则使用组3，如果数组各不相同，就使用组6
      // 存在相同的数字
      // if(len === numSet.size){
        for(let i=0;i<len;i++){
          for(let j=0;j<len;j++){
            for(let k=0;k<len;k++){
              if(i!==j && j!==k && i!==k){
                let temp = `${numList[i]}${numList[j]}${numList[k]}`
                resNumList.push(temp)
              }
            }
          }
        }
      return Array.from(new Set(resNumList))
    },
    getZuXuanNums(numList, zuXuanNum){
      // 组选 123
      let resList = []
      for(let i=0;i<numList.length;i++){
        let itemNumStr = numList[i]
        let spreadZuNums = this.getSpreadZuNums(itemNumStr)
        for(let j=0;j<zuXuanNum;j++){
          resList = resList.concat(spreadZuNums)
        }
      }
      return resList
    },
    spreadNums() {
      // 根据号码的重复次数，将号码展开
      let allNums = []
      // console.log('this.tempTimesResult:',this.tempTimesResult)
      this.historyList.forEach((item) => {
        let numList = item.numList
        // 单选
        if (item.times.danXuanNum > 0) {
          for (let i = 0; i < item.times.danXuanNum; i++) {
            allNums = allNums.concat(numList)
          }
        }
        if (item.times.zuXuanNum > 0) {
          // 组选
          let nums = this.getZuXuanNums(numList, item.times.zuXuanNum)
          allNums = allNums.concat(nums)
        }
        if (item.times.fuDanNum > 0) {
          let nums = this.getZuXuanNums(numList, item.times.fuDanNum)
          allNums = allNums.concat(nums)
        }
      })
      return allNums
    },
    countAllNumsTime(allNums) {
      console.log('allNums:', allNums)
      // 计算所有号码出现的次数
      let resObj = {}
      allNums.forEach((item) => {
        if (item) {
          if (resObj[item]) {
            resObj[item]++
          } else {
            resObj[item] = 1
          }
        }
      })
      // 对出现次数相同的进行归类和排序
      let tempGroupResult = {}
      for (let key in resObj) {
        let num = resObj[key]
        if (tempGroupResult[num]) {
          tempGroupResult[num].push(key)
        } else {
          tempGroupResult[num] = [key]
        }
      }
      // 先按次数从大道小进行排序
      /**
        排序后的结果
        {
          2:[456,123]
          1:[789]
        }
       */
      console.log('tempGroupResult:', tempGroupResult)
      let groupResultKeys = Object.keys(tempGroupResult)
      groupResultKeys.sort((a, b) => {
        return b - a
      })
      console.log('groupResultKeys:', groupResultKeys)
      let finalResult = []
      // 再对同样次数的数组进行排序 // 将对象结果转成数组
      for (let key of groupResultKeys) {
        console.log('tempGroupResult[key]:', tempGroupResult[key])
        tempGroupResult[key].sort()
        tempGroupResult[key].forEach((num) => {
          finalResult.push({
            times: key,
            number: num
          })
        })
      }
      ElMessage({
        message: '处理成功',
        type: 'success'
      })
      console.log('finalResult:', finalResult)
      this.finalResult = finalResult
    },
    downloadFile() {
      // 超出免费限制
      // 超出免费限制
      if (isReqOverflow()) {
        adminDialog.show()
        return
      }
      let str = ''
      for (let item of this.finalResult) {
        str += `${item.number}：${item.times}\n`
      }
      let blob = new Blob([str], { type: 'text/plain;charset=utf-8' })
      downFile('统计结果_' + getShortTodayStr() + '.txt', blob)
    },
    downloadExcel() {
      // 超出免费限制
      // 超出免费限制
      if (isReqOverflow()) {
        adminDialog.show()
        return
      }
      let wb = XLSX.utils.book_new()
      // groupResult [{num:1,valueStr:'1',valueList:['1']}]
      let finalResult = this.finalResult
      let colNum = 0

      let excelAoa = []
      let header = ['号码', '出现次数']

      excelAoa.push(header)
      finalResult.forEach((item) => {
        let row = [item.number, item.times]
        excelAoa.push(row)
      })
      let excelWorkSheet = XLSX.utils.aoa_to_sheet(excelAoa)
      XLSX.utils.book_append_sheet(wb, excelWorkSheet, '统计结果')
      let abuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
      let blob = new Blob([abuffer], { type: 'application/octet-stream' })
      downFile('统计结果_' + getShortTodayStr() + '.xlsx', blob)
    },
    deleteThisHistory(historyItem){
      let that = this
      let id = historyItem._id
      ElMessageBox.confirm('确定要删除该记录吗?','提示',{
        confirmButtonText: '保存',
          cancelButtonText: '取消',
          type: 'warning'
      }
      ).then(()=>{
        request('/fucai3d/deleteHistory',{
          method:'post',
          body:{
            id:id
          }
        }).then(res=>{
          ElMessage({
            message: '删除成功',
            type: 'success'
          })
          that.getHistoryList()
          
        })
      })
    },
    async getHistoryList(){
      let userInfo = getUserInfo()
      this.finalResult = null
      let data = await request('/fucai3d/getHistory?id='+userInfo._id)
      console.log('data:',data)
      this.historyList = data
    }
  },
  mounted(){
    this.getHistoryList()  
  }
}
</script>
<style lang="scss" scoped>
  .container{
    padding:20px;
    background-color: white;
    .history-container{
      background-color: #eee;
      padding:10px;
      .history-item{
        margin-top: 20px;
        .item-wrap{
          display: flex;
          align-items: flex-start;
          margin-top: 4px;
          .label{
            width: 60px;
            flex-shrink: 0;
          }
        }
      }
    }
    .btn-group{
      margin-top: 20px;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
    .result-wrap{
    // background-color: #f5f5f5;

    .title{
      margin-top: 32px;
      font-weight: bold;
      .link-btn{
        margin-left: 20px;
        text-decoration: underline;
        cursor: pointer;
        color:blue
        
      }
    }
    .tools-wrap{
      margin-top: 20px;
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }
    .result-list-wrap{
      margin-top: 20px;
      background-color: #f5f5f5;
      padding:10px 10px 20px;
      box-sizing: border-box;
      border-radius: 4px;
    }
    .times-result-item{
      margin-top: 20px;
      .item{
        display: flex;
        align-items: flex-start;
        margin-top: 4px;
        .label{
          flex-shrink: 0;
          word-break: keep-all;
          width: 60px;
          flex-shrink: 0;
        }
      }
    }
    .result-item{
      word-break: break-all;
      margin-top: 20px;
      display: flex;
      align-items: flex-start;
      .label{
        flex-shrink: 0;
        word-break: keep-all;
        width: 40px;
        flex-shrink: 0;
      }
      .res-value{
        margin-left: 10px;
        color:red;
        word-break: break-word;
      }
    }
  }
  }
</style>